#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include "h/memutils.h"

unsigned long const N = 10000000;
int sz = 1024 * 1024 * 22;


void test_speed ()
{
	struct timeval starttime,endtime;
	long int timeuse;
	
	gettimeofday(&starttime,0);
	unsigned long i; 
	for ( i = 0; i < N; i++ )
	{
		char* tmp = malloc(sz);
		free(tmp);
	}
	gettimeofday(&endtime,0);
	timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;
	printf ("%d us\n", timeuse);
	double a = timeuse;

	gettimeofday(&starttime,0);
	for ( i = 0; i < N; i++ )
	{
		char* tmp = palloc(sz);
		pfree(tmp);
	}
	gettimeofday(&endtime,0);
	timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;
	printf ("%d us\n", timeuse);
	double b = timeuse;
	double x = (b-a)/a;
	printf ("(b-a)/a = %f\n", x);
}

int main ()
{
	MemoryContextInit();
	PostmasterContext = AllocSetContextCreate(TopMemoryContext,
											  "Postmaster",
											  ALLOCSET_DEFAULT_MINSIZE,
											  ALLOCSET_DEFAULT_INITSIZE,
											  ALLOCSET_DEFAULT_MAXSIZE);
	//test_speed();
	
	printf ("curr mem: %s\n", CurrentMemoryContext->name);
	MemoryContextSwitchTo(PostmasterContext);
	printf ("curr mem: %s\n", CurrentMemoryContext->name);

	char* p = palloc(32768);
	p[0] = 'a';
	p[1] = 'a';
	p[2] = 'a';
	printf ("%p\n", p);
	printf ("%s\n", p);
	pfree(p);
	return 0;
}
